
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include<linux/input.h>
#include <sys/select.h>


/*
 * ./ts_test /dev/input/event1
 */



//select方式
int main(int argc, char** argv)
{
    int fd;
	ssize_t readlen;
	int len = sizeof(struct input_event);
	struct input_event ev;
	fd_set rfds;
    struct timeval tv;
    int retval;
	
    if(argc != 2)
	{
	    printf("Usage:%s <dev>\n",argv[0]);
		return -1;
	}
	
    //打开设备
    fd = open(argv[1], O_NONBLOCK|O_RDWR);//非阻塞方式：CPU利用率高
    //fd = open(argv[1], O_RDWR);  //阻塞方式
	if(fd == -1)
	{
	    printf("%s open error\n",argv[1]);
		return -1;
	}

	
    //读取设备
    while(1)
    {
    
	   FD_ZERO(&rfds);
	   FD_SET(fd, &rfds);  //设置rfd的bit fd为1，表示要监测文件句柄fd
	   tv.tv_sec = 5;      //时间设置放进循环是因为时间会更新
       tv.tv_usec = 0;

       retval = select(fd + 1, &rfds, NULL, NULL, &tv); //第一个参数应该被设置为最大的fd加1
       if (retval == -1)
       	{
           printf("select error\n");
		   return -1;
       	}
       else if (retval == 0)
       	{
           printf("timeout\n");
       	}
       else
       {
	        readlen = read(fd, &ev, len);
	  		if(len == readlen)
	  		{
	  		  printf("Get : type = 0x%3x, code = 0x%3x, value = %d \n",ev.type, ev.code, ev.value);
	  		}
       }
     
   }
   return 0;
}
